package cn.schoolwow.quickapi.module.common.flow;

import cn.schoolwow.quickapi.domain.QuickAPIOption;
import cn.schoolwow.quickapi.module.common.domain.APIDocument;
import cn.schoolwow.quickapi.module.common.domain.APIEntity;
import cn.schoolwow.quickapi.module.common.domain.APIField;
import cn.schoolwow.quickapi.util.QuickAPIUtil;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;
import java.util.Stack;

public class GetRecycleClassNameFlow implements BusinessFlow {
    private Logger logger = LoggerFactory.getLogger(GetRecycleClassNameFlow.class);

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickAPIOption quickAPIOption = flowContext.checkInstanceData(QuickAPIOption.class);

        if(null==quickAPIOption.entityPackageNameList||quickAPIOption.entityPackageNameList.isEmpty()){
            return;
        }

        Set<String> classNameSet = (Set<String>) flowContext.getData("classNameSet");
        Class rootClazz = (Class) flowContext.checkData("rootClazz");
        APIDocument apiDocument = flowContext.checkInstanceData(APIDocument.class);

        Stack<Class> apiEntityClassStack = new Stack();
        apiEntityClassStack.push(rootClazz);
        while(!apiEntityClassStack.isEmpty()){
            Class clazz = apiEntityClassStack.pop();

            boolean match = false;
            for(String entityPackageName:quickAPIOption.entityPackageNameList){
                if(clazz.getName().startsWith(entityPackageName)){
                    match = true;
                    break;
                }
            }
            if(!match){
                continue;
            }

            APIEntity apiEntity = QuickAPIUtil.getAPIEntity(clazz);
            classNameSet.add(apiEntity.className);
            if(!apiDocument.apiEntityMap.containsKey(apiEntity.className)){
                apiDocument.apiEntityMap.put(apiEntity.className,apiEntity);
            }
            for(APIField apiField:apiEntity.apiFieldList){
                if(!classNameSet.contains(apiField.field.getType().getName())){
                    apiEntityClassStack.push(apiField.field.getType());
                }
                if(null!=apiField.genericTypeClassName&&!classNameSet.contains(apiField.genericTypeClassName)){
                    if(!"T".equalsIgnoreCase(apiField.genericTypeClassName)){
                        try {
                            apiEntityClassStack.push(ClassLoader.getSystemClassLoader().loadClass(apiField.genericTypeClassName));
                        } catch (ClassNotFoundException e) {
                            logger.warn("[找不到字段泛型类]{}",e.getMessage());
                        }
                    }
                }
            }
        }
    }

    @Override
    public String name() {
        return "获取所有相关实体类信息";
    }
}
